import time

from VizSpread.appengine.contactsparser import ContactsParser, DuplicateDatasetError
from VizSpread.appengine.models import Dataset, Contact

from VizSpread.tests import testdata

from google.appengine.ext import db
from google.appengine.api.users import User

class TestExceptions():

	def test_duplicate_dataset_name_error(self):
		try:
			raise DuplicateDatasetError("SetName", "Massage")
		except DuplicateDatasetError, error:
			assert error.name == "SetName"
			assert error.message == "Massage"
		else:
			assert False
			
class TestContactsParser():

	def setup(self):
		self.defaultData=testdata.DEFAULT_DATA
		self.dataCentre = "14 Bond Street, London, UK"
		self.user = User("test3@foo.com")

	def test_contacts_parser_init(self):
		dataSetName = str(time.time())
		parser = ContactsParser(dataSetName, self.dataCentre, self.defaultData, self.user)
		assert parser
		
	def test_valid_data_is_validated(self):
		dataSetName = str(time.time())
		parser = ContactsParser(dataSetName, self.dataCentre, self.defaultData, self.user)
		assert parser.isValidData()

	def test_non_valid_data_is_not_validated(self):
		dataSetName = str(time.time())
		parser = ContactsParser(dataSetName, self.dataCentre, testdata.INVALID_HEADERS_DATA, self.user)
		assert not parser.isValidData()
	
	def test_parser_creates_dataset(self):
		dataSetName = str(time.time())
		parser = ContactsParser(dataSetName, self.dataCentre, self.defaultData, self.user)
		dataset = parser.createDataset()
		fetched_dataset = Dataset.all().filter('name =', dataSetName).fetch(1)[0]
		assert fetched_dataset.name == dataSetName
		assert fetched_dataset.dataCentre == self.dataCentre
		assert fetched_dataset.owner == self.user

	def test_parser_disallows_duplicate_dataset_names(self):
		dataSetName = str(time.time())
		dataset1 = Dataset(name=dataSetName, owner=self.user)
		dataset1.put()
		parser = ContactsParser(dataSetName, self.dataCentre, self.defaultData, self.user)
		
		try:
			datset2 = parser.createDataset()
		except DuplicateDatasetError:
			assert True
		else:
			assert False
		
	def test_parser_creates_contact(self):
		dataSetName = str(time.time())
		dataset = Dataset(name=dataSetName, owner=self.user)
		dataset.put()
		parser = ContactsParser(dataSetName, self.dataCentre, self.defaultData, self.user)
		
		name = "John Smith"
		email = "test6@bar.com"
		address = "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"
		geodataJSON = testdata.GEOCODE_JSON_OB
		
		contact = parser.createContact(dataset, name, email, geodataJSON)

		fetched_contact = Contact.all().filter('set =', dataset).fetch(1)[0]
		assert fetched_contact.name == name
		assert fetched_contact.email == email
		assert fetched_contact.address == address
		assert fetched_contact.geocodeResultJsonOb == geodataJSON




